<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>珠峰架构师成长计划</title>
    <link rel="stylesheet" type="text/css" href="../static/css/main.css">
</head>
<body>
<div class="nav">
    <div class="logo">
        
            珠峰架构师成长计划
        
    </div>
<ul><li><a href="../index.html">0.Async</a></li><li><a href="../html/0.editor.html">0.editor</a></li><li><a href="../html/0.module.html">0.module</a></li><li><a href="../html/1.ES2015.html">1.ES2015</a></li><li><a href="../html/2.Promise.html">2.Promise</a></li><li><a href="../html/3.Node.html">3.Node</a></li><li><a href="../html/4.NodeInstall.html">4.NodeInstall</a></li><li><a href="../html/5.REPL.html">5.REPL</a></li><li><a href="../html/6.NodeCore.html">6.NodeCore</a></li><li><a href="../html/7.module&NPM.html">7.module&NPM</a></li><li><a href="../html/8.Encoding.html">8.Encoding</a></li><li><a href="../html/9.Buffer.html">9.Buffer</a></li><li><a href="../html/10.fs.html">10.fs</a></li><li><a href="../html/11.Stream-1.html">11.Stream-1</a></li><li><a href="../html/11.Stream-2.html">11.Stream-2</a></li><li><a href="../html/11.Stream-3.html">11.Stream-3</a></li><li><a href="../html/11.Stream-4.html">11.Stream-4</a></li><li><a href="../html/12-Network-2.html">12-Network-2</a></li><li><a href="../html/12.NetWork-3.html">12.NetWork-3</a></li><li><a href="../html/12.Network-1.html">12.Network-1</a></li><li><a href="../html/13.tcp.html">13.tcp</a></li><li><a href="../html/14.http-1.html">14.http-1</a></li><li><a href="../html/14.http-2.html">14.http-2</a></li><li><a href="../html/15.compress.html">15.compress</a></li><li><a href="../html/16.crypto.html">16.crypto</a></li><li><a href="../html/17.process.html">17.process</a></li><li><a href="../html/18.yargs.html">18.yargs</a></li><li><a href="../html/19.cache.html">19.cache</a></li><li><a href="../html/20.action.html">20.action</a></li><li><a href="../html/21.https.html">21.https</a></li><li><a href="../html/22.cookie.html">22.cookie</a></li><li><a href="../html/23.session.html">23.session</a></li><li><a href="../html/24.express-1.html">24.express-1</a></li><li><a href="../html/24.express-2.html">24.express-2</a></li><li><a href="../html/24.express-3.html">24.express-3</a></li><li><a href="../html/24.express-4.html">24.express-4</a></li><li><a href="../html/25.koa-1.html">25.koa-1</a></li><li><a href="../html/26.webpack-1-basic.html">26.webpack-1-basic</a></li><li><a href="../html/26.webpack-2-optimize.html">26.webpack-2-optimize</a></li><li><a href="../html/26.webpack-3.tapable.html">26.webpack-3.tapable</a></li><li><a href="../html/26.webpack-4-AST.html">26.webpack-4-AST</a></li><li><a href="../html/26.webpack-5-source.html">26.webpack-5-source</a></li><li><a href="../html/26.webpack-6-loader.html">26.webpack-6-loader</a></li><li><a href="../html/26.webpack-7-plugin.html">26.webpack-7-plugin</a></li><li><a href="../html/26.webpack-8-hand.html">26.webpack-8-hand</a></li><li><a href="../html/27.react-1.html">27.react-1</a></li><li><a href="../html/27.react-2.html">27.react-2</a></li><li><a href="../html/27.react-3.html">27.react-3</a></li><li><a href="../html/27.react-4-immutable.html">27.react-4-immutable</a></li><li><a href="../html/27.react-5-react-dom-diff.html">27.react-5-react-dom-diff</a></li><li><a href="../html/27.react-6.html">27.react-6</a></li><li><a href="../html/28.react-mobx.html">28.react-mobx</a></li><li><a href="../html/28.redux-0.html">28.redux-0</a></li><li><a href="../html/28.redux-1.html">28.redux-1</a></li><li><a href="../html/28.redux-2-中间件.html">28.redux-2-中间件</a></li><li><a href="../html/28.redux-3-saga.html">28.redux-3-saga</a></li><li><a href="../html/28.redux-jwt-back.html">28.redux-jwt-back</a></li><li><a href="../html/28.redux-jwt-front.html">28.redux-jwt-front</a></li><li><a href="../html/29.mongodb-1.html">29.mongodb-1</a></li><li><a href="../html/29.mongodb-2.html">29.mongodb-2</a></li><li><a href="../html/29.mongodb-3.html">29.mongodb-3</a></li><li><a href="../html/29.mongodb-4.html">29.mongodb-4</a></li><li><a href="../html/29.mongodb-5.html">29.mongodb-5</a></li><li><a href="../html/29.mongodb-6.html">29.mongodb-6</a></li><li><a href="../html/30.cms-1-mysql.html">30.cms-1-mysql</a></li><li><a href="../html/30.cms-2-mysql.html">30.cms-2-mysql</a></li><li><a href="../html/30.cms-3-mysql.html">30.cms-3-mysql</a></li><li><a href="../html/30.cms-4-egg.html">30.cms-4-egg</a></li><li><a href="../html/30.cms-5-api.html">30.cms-5-api</a></li><li><a href="../html/30.cms-6-roadhog.html">30.cms-6-roadhog</a></li><li><a href="../html/30.cms-7-umi.html">30.cms-7-umi</a></li><li><a href="../html/30.cms-8-dva.html">30.cms-8-dva</a></li><li><a href="../html/30.cms-9-dva.html">30.cms-9-dva</a></li><li><a href="../html/30.cms-10-front.html">30.cms-10-front</a></li><li><a href="../html/30.cms-11-deploy.html">30.cms-11-deploy</a></li><li><a href="../html/33.redis.html">33.redis</a></li><li><a href="../html/34.unittest.html">34.unittest</a></li><li><a href="../html/35.jwt.html">35.jwt</a></li><li><a href="../html/36.websocket-1.html">36.websocket-1</a></li><li><a href="../html/36.websocket-2.html">36.websocket-2</a></li><li><a href="../html/38.chat-api-1.html">38.chat-api-1</a></li><li><a href="../html/38.chat-api-2.html">38.chat-api-2</a></li><li><a href="../html/38.chat-3.html">38.chat-3</a></li><li class="active"><a href="../html/38.chat-api-3.html">38.chat-api-3</a></li><li><a href="../html/38.chat.html">38.chat</a></li><li><a href="../html/38.chat2.html">38.chat2</a></li><li><a href="../html/38.chat2.html">38.chat2</a></li><li><a href="../html/39.crawl-0.html">39.crawl-0</a></li><li><a href="../html/39.crawl-1.html">39.crawl-1</a></li><li><a href="../html/39.crawl-2.html">39.crawl-2</a></li><li><a href="../html/40.deploy.html">40.deploy</a></li><li><a href="../html/41.safe.html">41.safe</a></li><li><a href="../html/42.test.html">42.test</a></li><li><a href="../html/43.nginx.html">43.nginx</a></li><li><a href="../html/44.enzyme.html">44.enzyme</a></li><li><a href="../html/45.docker.html">45.docker</a></li><li><a href="../html/46.elastic.html">46.elastic</a></li><li><a href="../html/47.oauth.html">47.oauth</a></li><li><a href="../html/48.wxpay.html">48.wxpay</a></li><li><a href="../html/49.nunjucks.html">49.nunjucks</a></li><li><a href="../html/50.ketang.html">50.ketang</a></li><li><a href="../html/index.html">index</a></li><li><a href="../html/51.typescript.html">51.typescript</a></li><li><a href="../html/52.UML.html">52.UML</a></li><li><a href="../html/53.design.html">53.design</a></li><li><a href="../html/index.html">index</a></li><li><a href="../html/54.linux.html">54.linux</a></li><li><a href="../html/55.yaml.html">55.yaml</a></li><li><a href="../html/50.ketang2.html">50.ketang2</a></li><li><a href="../html/56.ts.html">56.ts</a></li><li><a href="../html/57.ts_react.html">57.ts_react</a></li><li><a href="../html/58.react-ssr.html">58.react-ssr</a></li><li><a href="../html/59.react-ssr.html">59.react-ssr</a></li></ul></div>


<div class="warpper">

    <div class="page-toc">
        <ul><li><a href="#t01.初始化项目">1.初始化项目</a></li><li><a href="#t12. 实现后端的登录接口">2. 实现后端的登录接口</a><ul><li><a href="#t22.1 app/model/user.js">2.1 app/model/user.js</a></li><li><a href="#t32.2 app/controller/user.js">2.2 app/controller/user.js</a></li><li><a href="#t42.3 app/controller/base.js">2.3 app/controller/base.js</a></li></ul></li><li><a href="#t53. 房间功能">3. 房间功能</a><ul><li><a href="#t63.1 app/router.js">3.1 app/router.js</a></li><li><a href="#t73.2 config/config.default.js">3.2 config/config.default.js</a></li><li><a href="#t83.3 config/plugin.js">3.3 config/plugin.js</a></li><li><a href="#t93.4 app/controller/rooms.js">3.4 app/controller/rooms.js</a></li><li><a href="#t103.5  app/model/room.js">3.5  app/model/room.js</a></li></ul></li><li><a href="#t114.聊天功能">4.聊天功能</a><ul><li><a href="#t124.1 app/controller/user.js">4.1 app/controller/user.js</a></li><li><a href="#t134.2 app/model/room.js">4.2 app/model/room.js</a></li><li><a href="#t144.3 app/model/user.js">4.3 app/model/user.js</a></li><li><a href="#t154.4 app/router.js">4.4 app/router.js</a></li><li><a href="#t164.5 config/config.default.js">4.5 config/config.default.js</a></li><li><a href="#t174.6 config/plugin.js">4.6 config/plugin.js</a></li><li><a href="#t184.7 package.json">4.7 package.json</a></li><li><a href="#t194.8 app/io/controller/messages.js">4.8 app/io/controller/messages.js</a></li><li><a href="#t204.9 app/io/middleware/connect.js">4.9 app/io/middleware/connect.js</a></li><li><a href="#t214.10 app/model/message.js">4.10 app/model/message.js</a></li><li><a href="#t224.11 server/app.js">4.11 server/app.js</a></li><li><a href="#t234.12 server/public/index.html">4.12 server/public/index.html</a></li></ul></li><li><a href="#t24参考">参考</a></li></ul>
    </div>
    
    <div class="content markdown-body">
        <h2 id="t01.&#x521D;&#x59CB;&#x5316;&#x9879;&#x76EE;">1.&#x521D;&#x59CB;&#x5316;&#x9879;&#x76EE; <a href="#t01.&#x521D;&#x59CB;&#x5316;&#x9879;&#x76EE;"> # </a></h2>
<pre><code class="lang-js">egg-init --type simple chat-api
</code></pre>
<h2 id="t12. &#x5B9E;&#x73B0;&#x540E;&#x7AEF;&#x7684;&#x767B;&#x5F55;&#x63A5;&#x53E3;">2. &#x5B9E;&#x73B0;&#x540E;&#x7AEF;&#x7684;&#x767B;&#x5F55;&#x63A5;&#x53E3; <a href="#t12. &#x5B9E;&#x73B0;&#x540E;&#x7AEF;&#x7684;&#x767B;&#x5F55;&#x63A5;&#x53E3;"> # </a></h2>
<h3 id="t22.1 app/model/user.js">2.1 app/model/user.js <a href="#t22.1 app/model/user.js"> # </a></h3>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-params">app</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> mongoose = app.mongoose;
    <span class="hljs-keyword">const</span> Schema = mongoose.Schema;

    <span class="hljs-keyword">const</span> UserSchema = <span class="hljs-keyword">new</span> Schema({
      <span class="hljs-attr">email</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>  }
    });

    <span class="hljs-keyword">return</span> mongoose.model(<span class="hljs-string">&apos;User&apos;</span>, UserSchema);
  }
</code></pre>
<h3 id="t32.2 app/controller/user.js">2.2 app/controller/user.js <a href="#t32.2 app/controller/user.js"> # </a></h3>
<p>app/controller/user.js</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Controller = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;./base&apos;</span>);

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span> </span>{
  <span class="hljs-keyword">async</span> login() {
      <span class="hljs-keyword">const</span> {ctx,app}=<span class="hljs-keyword">this</span>;
      <span class="hljs-keyword">let</span> body = ctx.request.body;
      <span class="hljs-keyword">let</span> oldUser = <span class="hljs-keyword">await</span> ctx.model.User.findOne({<span class="hljs-attr">email</span>: body.email});
      <span class="hljs-keyword">if</span> (oldUser) {
          ctx.session.user=oldUser;
          <span class="hljs-keyword">this</span>.success(oldUser);
      } <span class="hljs-keyword">else</span> {
          <span class="hljs-keyword">let</span> newUser=<span class="hljs-keyword">new</span> ctx.model.User(body);
          <span class="hljs-keyword">await</span> newUser.save();
          ctx.session.user=newUser;
          <span class="hljs-keyword">this</span>.success(newUser);
      }
  }
}

<span class="hljs-built_in">module</span>.exports = UserController;
</code></pre>
<h3 id="t42.3 app/controller/base.js">2.3 app/controller/base.js <a href="#t42.3 app/controller/base.js"> # </a></h3>
<p>app/controller/base.js</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Controller = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;egg&apos;</span>).Controller;
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BaseController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span> </span>{
    success(data) {
        <span class="hljs-keyword">this</span>.ctx.body={
            <span class="hljs-attr">code</span>: <span class="hljs-number">0</span>,
            data
          }
    }
    error(error) {
        <span class="hljs-keyword">this</span>.ctx.body={
            <span class="hljs-attr">code</span>: <span class="hljs-number">1</span>,
            error
          }
    }
}

<span class="hljs-built_in">module</span>.exports = BaseController;
</code></pre>
<h2 id="t53. &#x623F;&#x95F4;&#x529F;&#x80FD;">3. &#x623F;&#x95F4;&#x529F;&#x80FD; <a href="#t53. &#x623F;&#x95F4;&#x529F;&#x80FD;"> # </a></h2>
<h3 id="t63.1 app/router.js">3.1 app/router.js <a href="#t63.1 app/router.js"> # </a></h3>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-params">app</span> =&gt;</span> {
  <span class="hljs-keyword">const</span> { router, controller } = app;
  router.post(<span class="hljs-string">&apos;/login&apos;</span>,controller.user.login);
  router.get(<span class="hljs-string">&apos;/rooms&apos;</span>,controller.rooms.list);
  router.post(<span class="hljs-string">&apos;/rooms&apos;</span>,controller.rooms.create);
};
</code></pre>
<h3 id="t73.2 config/config.default.js">3.2 config/config.default.js <a href="#t73.2 config/config.default.js"> # </a></h3>
<p>config/config.default.js</p>
<pre><code class="lang-js">config.mongoose = {
    <span class="hljs-attr">client</span>: {
      <span class="hljs-attr">url</span>: <span class="hljs-string">&apos;mongodb://127.0.0.1/chat&apos;</span>,
      <span class="hljs-attr">options</span>: {},
    },
  };

  config.security={
    <span class="hljs-attr">csrf</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">domainWhiteList</span>:[<span class="hljs-string">&apos;http://127.0.0.1:8000&apos;</span>]
  }
</code></pre>
<h3 id="t83.3 config/plugin.js">3.3 config/plugin.js <a href="#t83.3 config/plugin.js"> # </a></h3>
<p>config/plugin.js</p>
<pre><code class="lang-js">exports.mongoose = {
    <span class="hljs-attr">enable</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">package</span>: <span class="hljs-string">&apos;egg-mongoose&apos;</span>,
};
exports.cors = {
    <span class="hljs-attr">enable</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">package</span>: <span class="hljs-string">&apos;egg-cors&apos;</span>,
};
</code></pre>
<h3 id="t93.4 app/controller/rooms.js">3.4 app/controller/rooms.js <a href="#t93.4 app/controller/rooms.js"> # </a></h3>
<p>app/controller/rooms.js</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Controller = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;./base&apos;</span>);

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RoomController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span> </span>{
  <span class="hljs-keyword">async</span> list() {
      <span class="hljs-keyword">const</span> {ctx,app}=<span class="hljs-keyword">this</span>;
      <span class="hljs-keyword">let</span> {keyword=<span class="hljs-string">&apos;&apos;</span>}=ctx.query;
      <span class="hljs-keyword">let</span> query={};
      <span class="hljs-keyword">if</span> (keyword) {
          query[<span class="hljs-string">&apos;name&apos;</span>]=<span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(keyword);
      }
      <span class="hljs-keyword">let</span> list = <span class="hljs-keyword">await</span> app.model.Room.find(query);
      <span class="hljs-keyword">this</span>.success(list);
  }
  <span class="hljs-keyword">async</span> create() {
      <span class="hljs-keyword">const</span> {ctx,app}=<span class="hljs-keyword">this</span>;
      <span class="hljs-keyword">let</span> body=ctx.request.body;
      <span class="hljs-keyword">let</span> oldRoom = <span class="hljs-keyword">await</span> app.model.Room.findOne({<span class="hljs-attr">name</span>: body.name});
      <span class="hljs-keyword">if</span> (oldRoom) {
          <span class="hljs-keyword">this</span>.error(<span class="hljs-string">&apos;&#x623F;&#x95F4;&#x540D;&#x5DF2;&#x7ECF;&#x5B58;&#x5728;&apos;</span>);
      } <span class="hljs-keyword">else</span> {
          <span class="hljs-keyword">let</span> newRoom=<span class="hljs-keyword">new</span> app.model.Room(body);
          <span class="hljs-keyword">await</span> newRoom.save();
          <span class="hljs-keyword">this</span>.success(newRoom);
      }
  }
}

<span class="hljs-built_in">module</span>.exports = RoomController;
</code></pre>
<h3 id="t103.5  app/model/room.js">3.5  app/model/room.js <a href="#t103.5  app/model/room.js"> # </a></h3>
<p>app/model/room.js</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-params">app</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> mongoose = app.mongoose;
    <span class="hljs-keyword">const</span> Schema = mongoose.Schema;

    <span class="hljs-keyword">const</span> RoomSchema = <span class="hljs-keyword">new</span> Schema({
      <span class="hljs-attr">name</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>  }
    });

    <span class="hljs-keyword">return</span> mongoose.model(<span class="hljs-string">&apos;Room&apos;</span>, RoomSchema);
  }
</code></pre>
<h2 id="t114.&#x804A;&#x5929;&#x529F;&#x80FD;">4.&#x804A;&#x5929;&#x529F;&#x80FD; <a href="#t114.&#x804A;&#x5929;&#x529F;&#x80FD;"> # </a></h2>
<h3 id="t124.1 app/controller/user.js">4.1 app/controller/user.js <a href="#t124.1 app/controller/user.js"> # </a></h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Controller = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;./base&apos;</span>);
<span class="hljs-keyword">const</span> gravatar=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;gravatar&apos;</span>);
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span> </span>{
  <span class="hljs-keyword">async</span> login() {
      <span class="hljs-keyword">const</span> {ctx,app}=<span class="hljs-keyword">this</span>;
      <span class="hljs-keyword">let</span> user = ctx.request.body;
      <span class="hljs-keyword">let</span> doc = <span class="hljs-keyword">await</span> ctx.model.User.findOne({<span class="hljs-attr">email</span>: user.email});
      <span class="hljs-keyword">if</span> (!doc) {
            user.name=user.email.split(<span class="hljs-string">&apos;@&apos;</span>)[<span class="hljs-number">0</span>];
            user.avatar=gravatar.url(user.email);
            doc=<span class="hljs-keyword">new</span> ctx.model.User(user);
            <span class="hljs-keyword">await</span> doc.save();
      } 
      <span class="hljs-keyword">let</span> token = app.jwt.sign(doc.toJSON(),app.config.jwt.secret);
      <span class="hljs-keyword">this</span>.success(token);
  }
}

<span class="hljs-built_in">module</span>.exports = UserController;
</code></pre>
<h3 id="t134.2 app/model/room.js">4.2 app/model/room.js <a href="#t134.2 app/model/room.js"> # </a></h3>
<p>app/model/room.js</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-params">app</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> mongoose = app.mongoose;
    <span class="hljs-keyword">const</span> Schema = mongoose.Schema;
    <span class="hljs-keyword">const</span> ObjectId=Schema.Types.ObjectId; 
    <span class="hljs-keyword">const</span> RoomSchema = <span class="hljs-keyword">new</span> Schema({
        <span class="hljs-attr">name</span>: {<span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>},
        <span class="hljs-attr">createAt</span>: {<span class="hljs-attr">type</span>: <span class="hljs-built_in">Date</span>,<span class="hljs-attr">default</span>: <span class="hljs-built_in">Date</span>.now},
        <span class="hljs-attr">creator</span>:{<span class="hljs-attr">type</span>:ObjectId,<span class="hljs-attr">ref</span>:<span class="hljs-string">&apos;User&apos;</span>}
    });

    <span class="hljs-keyword">return</span> mongoose.model(<span class="hljs-string">&apos;Room&apos;</span>, RoomSchema);
}
</code></pre>
<h3 id="t144.3 app/model/user.js">4.3 app/model/user.js <a href="#t144.3 app/model/user.js"> # </a></h3>
<p>app/model/user.js</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-params">app</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> mongoose = app.mongoose;
    <span class="hljs-keyword">const</span> Schema = mongoose.Schema;
    <span class="hljs-keyword">const</span> ObjectId=Schema.Types.ObjectId; 
    <span class="hljs-keyword">const</span> UserSchema=<span class="hljs-keyword">new</span> Schema({
        <span class="hljs-attr">name</span>: <span class="hljs-built_in">String</span>,
        <span class="hljs-attr">avatar</span>:<span class="hljs-built_in">String</span>,
        <span class="hljs-attr">email</span>: {<span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>},
        <span class="hljs-attr">room</span>: {<span class="hljs-attr">type</span>: ObjectId,<span class="hljs-attr">ref</span>: <span class="hljs-string">&apos;Room&apos;</span>},
        <span class="hljs-attr">socket</span>:{<span class="hljs-attr">type</span>:<span class="hljs-built_in">String</span>},
        <span class="hljs-attr">online</span>:{<span class="hljs-attr">type</span>:<span class="hljs-built_in">Boolean</span>,<span class="hljs-attr">default</span>:<span class="hljs-literal">false</span>}
    });

    <span class="hljs-keyword">return</span> mongoose.model(<span class="hljs-string">&apos;User&apos;</span>, UserSchema);
  }
</code></pre>
<h3 id="t154.4 app/router.js">4.4 app/router.js <a href="#t154.4 app/router.js"> # </a></h3>
<p>app/router.js</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-params">app</span> =&gt;</span> {
  <span class="hljs-keyword">const</span> { router, controller,io } = app;
  router.post(<span class="hljs-string">&apos;/login&apos;</span>,controller.user.login);
  router.get(<span class="hljs-string">&apos;/rooms&apos;</span>,controller.rooms.list);
  router.post(<span class="hljs-string">&apos;/rooms&apos;</span>,controller.rooms.create);
  io.route(<span class="hljs-string">&apos;getRoom&apos;</span>,io.controller.messages.getRoom);
  io.route(<span class="hljs-string">&apos;addMessage&apos;</span>,io.controller.messages.addMessage);
};
</code></pre>
<h3 id="t164.5 config/config.default.js">4.5 config/config.default.js <a href="#t164.5 config/config.default.js"> # </a></h3>
<p>config/config.default.js</p>
<pre><code class="lang-js"><span class="hljs-meta">&apos;use strict&apos;</span>;

<span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-params">appInfo</span> =&gt;</span> {
  <span class="hljs-keyword">const</span> config = exports = {};

  <span class="hljs-comment">// use for cookie sign key, should change to your own and keep security</span>
  config.keys = appInfo.name + <span class="hljs-string">&apos;_1533636529759_8753&apos;</span>;

  <span class="hljs-comment">// add your config here</span>
  config.middleware=[];

  config.mongoose = {
    <span class="hljs-attr">client</span>: {
      <span class="hljs-attr">url</span>: <span class="hljs-string">&apos;mongodb://127.0.0.1/chat&apos;</span>,
      <span class="hljs-attr">options</span>: {},
    },
  };

  config.security={
    <span class="hljs-attr">csrf</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">domainWhiteList</span>:[<span class="hljs-string">&apos;http://127.0.0.1:8000&apos;</span>]
  }
  config.io = {
    <span class="hljs-attr">init</span>: { <span class="hljs-attr">wsEngine</span>: <span class="hljs-string">&apos;ws&apos;</span> }, <span class="hljs-comment">// default: ws</span>
    namespace: {
      <span class="hljs-string">&apos;/&apos;</span>: {
        <span class="hljs-attr">connectionMiddleware</span>: [<span class="hljs-string">&apos;connect&apos;</span>],
        <span class="hljs-attr">packetMiddleware</span>: [],
      }
    },
    <span class="hljs-attr">redis</span>: {
      <span class="hljs-attr">host</span>: <span class="hljs-string">&apos;127.0.0.1&apos;</span>,
      <span class="hljs-attr">port</span>: <span class="hljs-number">6379</span>
    },
  };
  config.jwt = {
    <span class="hljs-attr">secret</span>: <span class="hljs-string">&apos;zfpx&apos;</span>
  }
  <span class="hljs-keyword">return</span> config;
};

</code></pre>
<h3 id="t174.6 config/plugin.js">4.6 config/plugin.js <a href="#t174.6 config/plugin.js"> # </a></h3>
<p>config/plugin.js</p>
<pre><code class="lang-js">exports.io = {
    <span class="hljs-attr">enable</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">package</span>: <span class="hljs-string">&apos;egg-socket.io&apos;</span>,
};

exports.jwt = {
    <span class="hljs-attr">enable</span>:<span class="hljs-literal">true</span>,
    <span class="hljs-attr">package</span>:<span class="hljs-string">&apos;egg-jwt&apos;</span>
}
</code></pre>
<h3 id="t184.7 package.json">4.7 package.json <a href="#t184.7 package.json"> # </a></h3>
<p>package.json</p>
<pre><code class="lang-js"><span class="hljs-string">&quot;scripts&quot;</span>: {
    <span class="hljs-string">&quot;start&quot;</span>: <span class="hljs-string">&quot;egg-scripts start --daemon --title=egg-server-chat-api --sticky&quot;</span>,
    <span class="hljs-string">&quot;stop&quot;</span>: <span class="hljs-string">&quot;egg-scripts stop --title=egg-server-chat-api&quot;</span>,
    <span class="hljs-string">&quot;dev&quot;</span>: <span class="hljs-string">&quot;egg-bin dev --sticky&quot;</span>,
    <span class="hljs-string">&quot;debug&quot;</span>: <span class="hljs-string">&quot;egg-bin debug&quot;</span>,
    <span class="hljs-string">&quot;test&quot;</span>: <span class="hljs-string">&quot;npm run lint -- --fix &amp;&amp; npm run test-local&quot;</span>,
    <span class="hljs-string">&quot;test-local&quot;</span>: <span class="hljs-string">&quot;egg-bin test&quot;</span>,
    <span class="hljs-string">&quot;cov&quot;</span>: <span class="hljs-string">&quot;egg-bin cov&quot;</span>,
    <span class="hljs-string">&quot;lint&quot;</span>: <span class="hljs-string">&quot;eslint .&quot;</span>,
    <span class="hljs-string">&quot;ci&quot;</span>: <span class="hljs-string">&quot;npm run lint &amp;&amp; npm run cov&quot;</span>,
    <span class="hljs-string">&quot;autod&quot;</span>: <span class="hljs-string">&quot;autod&quot;</span>
}
</code></pre>
<h3 id="t194.8 app/io/controller/messages.js">4.8 app/io/controller/messages.js <a href="#t194.8 app/io/controller/messages.js"> # </a></h3>
<p>app/io/controller/messages.js</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> {Controller}=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;egg&apos;</span>);
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MessageController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span></span>{
    <span class="hljs-keyword">async</span> addMessage() {
        <span class="hljs-keyword">let</span> {app,ctx}=<span class="hljs-keyword">this</span>;
        <span class="hljs-keyword">let</span> message=ctx.args[<span class="hljs-number">0</span>];<span class="hljs-comment">// {user,room,content}</span>
        <span class="hljs-keyword">let</span> newMessage=<span class="hljs-keyword">new</span> app.model.Message(message);
        <span class="hljs-keyword">await</span> newMessage.save();
        <span class="hljs-keyword">let</span> doc=<span class="hljs-keyword">await</span> app.model.Message.findById(newMessage._id).populate(<span class="hljs-string">&apos;user&apos;</span>);
        app.io.to(message.room).emit(<span class="hljs-string">&apos;messageAdded&apos;</span>,doc.toJSON());
    }
    <span class="hljs-keyword">async</span> getRoom() {
        <span class="hljs-keyword">let</span> {app,ctx}=<span class="hljs-keyword">this</span>;
        <span class="hljs-keyword">let</span> room=ctx.args[<span class="hljs-number">0</span>];
        <span class="hljs-keyword">let</span> users=<span class="hljs-keyword">await</span> app.model.User.find({room,<span class="hljs-attr">online</span>:<span class="hljs-literal">true</span>});
        <span class="hljs-keyword">let</span> messages = <span class="hljs-keyword">await</span> app.model.Message.find({room}).sort({<span class="hljs-attr">createAt</span>:<span class="hljs-number">-1</span>}).populate(<span class="hljs-string">&apos;user&apos;</span>).sort({<span class="hljs-attr">createAt</span>: <span class="hljs-number">-1</span>}).limit(<span class="hljs-number">20</span>);
        ctx.socket.emit(<span class="hljs-string">&apos;room&apos;</span>,{users,<span class="hljs-attr">messages</span>:messages.reverse()});
    }
}
<span class="hljs-built_in">module</span>.exports=MessageController;
</code></pre>
<h3 id="t204.9 app/io/middleware/connect.js">4.9 app/io/middleware/connect.js <a href="#t204.9 app/io/middleware/connect.js"> # </a></h3>
<p>app/io/middleware/connect.js</p>
<pre><code class="lang-js"><span class="hljs-comment">// {app_root}/app/io/middleware/packet.js</span>
<span class="hljs-keyword">const</span> SYSTEM = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">&apos;&#x7CFB;&#x7EDF;&apos;</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">&apos;<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f293969f9b9cb2c3c0c4dc919d9f">[email&#160;protected]</a>&apos;</span>,
    <span class="hljs-attr">avatar</span>: <span class="hljs-string">&apos;http://www.gravatar.com/avatar/1e6fd8e56879c84999cd481255530592&apos;</span>
}
<span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-params">app</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">async</span> (ctx, next) =&gt; {
        <span class="hljs-keyword">const</span> {app,socket,<span class="hljs-attr">query</span>: {room,token}}=ctx;
        <span class="hljs-keyword">if</span> (token) {
            <span class="hljs-keyword">let</span> decodeUser=app.jwt.verify(token,app.config.jwt.secret);
            <span class="hljs-keyword">if</span> (decodeUser) {
                <span class="hljs-keyword">let</span> oldUser=<span class="hljs-keyword">await</span> app.model.User.findById(decodeUser._id);
                <span class="hljs-keyword">let</span> oldSocket=oldUser.socket;
                 <span class="hljs-keyword">if</span> (oldSocket) {
                    app.io.of(<span class="hljs-string">&apos;/&apos;</span>).adapter.remoteDisconnect(oldSocket, <span class="hljs-literal">true</span>, err =&gt; {
                        app.logger.error(err);
                    });
                } 
                oldUser.room=room;
                oldUser.online=<span class="hljs-literal">true</span>;
                oldUser.socket=socket.id;
                <span class="hljs-keyword">await</span> oldUser.save();
                socket.join(room);
                socket.broadcast.to(room).emit(<span class="hljs-string">&apos;online&apos;</span>,oldUser.toJSON());
                socket.broadcast.to(room).emit(<span class="hljs-string">&apos;messageAdded&apos;</span>,{
                    <span class="hljs-attr">user</span>: SYSTEM,
                    <span class="hljs-attr">content</span>:<span class="hljs-string">`&#x7528;&#x6237;<span class="hljs-subst">${oldUser.name}</span>&#x52A0;&#x5165;&#x804A;&#x5929;&#x5BA4;`</span>
                });
                <span class="hljs-keyword">await</span> next();
                socket.leave(room);
                socket.broadcast.to(room).emit(<span class="hljs-string">&apos;offline&apos;</span>,oldUser._id);
                socket.broadcast.to(room).emit(<span class="hljs-string">&apos;messageAdded&apos;</span>,{
                    <span class="hljs-attr">user</span>: SYSTEM,
                    <span class="hljs-attr">content</span>:<span class="hljs-string">`&#x7528;&#x6237;<span class="hljs-subst">${oldUser.name}</span>&#x79BB;&#x5F00;&#x4E86;&#x804A;&#x5929;&#x5BA4;`</span>
                });
                oldUser.room=<span class="hljs-literal">null</span>;
                oldUser.online=<span class="hljs-literal">null</span>;
                oldUser.socket=<span class="hljs-literal">null</span>;
                <span class="hljs-keyword">await</span> oldUser.save();
            }<span class="hljs-keyword">else</span> {
                socket.emit(<span class="hljs-string">&apos;needLogin&apos;</span>,<span class="hljs-string">&apos;&#x4F60;&#x9700;&#x8981;&#x5148;&#x767B;&#x5F55;&apos;</span>);
            }
        } <span class="hljs-keyword">else</span> {
            socket.emit(<span class="hljs-string">&apos;needLogin&apos;</span>,<span class="hljs-string">&apos;&#x4F60;&#x9700;&#x8981;&#x5148;&#x767B;&#x5F55;&apos;</span>);
        }
    };
};
</code></pre>
<h3 id="t214.10 app/model/message.js">4.10 app/model/message.js <a href="#t214.10 app/model/message.js"> # </a></h3>
<p>app/model/message.js</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-params">app</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> mongoose = app.mongoose;
    <span class="hljs-keyword">const</span> Schema = mongoose.Schema;
    <span class="hljs-keyword">const</span> ObjectId=Schema.Types.ObjectId; 
    <span class="hljs-keyword">const</span> RoomSchema = <span class="hljs-keyword">new</span> Schema({
        <span class="hljs-attr">user</span>: {<span class="hljs-attr">type</span>: ObjectId,<span class="hljs-attr">ref</span>: <span class="hljs-string">&apos;User&apos;</span>},
        <span class="hljs-attr">content</span>: <span class="hljs-built_in">String</span>,
        <span class="hljs-attr">room</span>:{<span class="hljs-attr">type</span>:ObjectId,<span class="hljs-attr">ref</span>:<span class="hljs-string">&apos;room&apos;</span>},
        <span class="hljs-attr">createAt</span>:{<span class="hljs-attr">type</span>:<span class="hljs-built_in">Date</span>,<span class="hljs-attr">default</span>:<span class="hljs-built_in">Date</span>.now}
    });
    <span class="hljs-keyword">return</span> mongoose.model(<span class="hljs-string">&apos;Message&apos;</span>, RoomSchema);
}
</code></pre>
<h3 id="t224.11 server/app.js">4.11 server/app.js <a href="#t224.11 server/app.js"> # </a></h3>
<p>server/app.js</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;express&apos;</span>);
<span class="hljs-keyword">var</span> app = express();
<span class="hljs-keyword">var</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;path&apos;</span>);
<span class="hljs-keyword">var</span> server = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;http&apos;</span>).createServer(app);
app.use(express.static(path.join(__dirname, <span class="hljs-string">&apos;public&apos;</span>)));
<span class="hljs-keyword">var</span> io = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;socket.io&apos;</span>)(server);
<span class="hljs-keyword">var</span> port = process.env.PORT || <span class="hljs-number">3000</span>;

server.listen(port, () =&gt; {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&apos;Server listening at port %d&apos;</span>, port);
});
</code></pre>
<h3 id="t234.12 server/public/index.html">4.12 server/public/index.html <a href="#t234.12 server/public/index.html"> # </a></h3>
<p>server/public/index.html</p>
<pre><code class="lang-js">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;
    &lt;title&gt;Document&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;button onclick=&quot;send()&quot;&gt;&#x53D1;&#x9001;&lt;/button&gt;
    &lt;script src=&quot;/socket.io/socket.io.js&quot;&gt;&lt;/script&gt;
    &lt;script&gt;
        let socket = io(&apos;http://localhost:7001/&apos;,{query:{room:&apos;default&apos;}});
        socket.on(&apos;connect&apos;, function () {
            console.log(&apos;&#x8FDE;&#x63A5;&#x6210;&#x529F;&apos;);
            socket.emit(&apos;getAllMessages&apos;);
        });
        socket.on(&apos;messageAdded&apos;, function (message) {
            console.log(message);
        });
        socket.on(&apos;allMessages&apos;, function (messages) {
            console.log(messages);
        });
        socket.on(&apos;message&apos;, function (message) {
            console.log(message);
        });
        socket.on(&apos;needLogin&apos;, function (message) {
            console.log(message);
        });

        function send() {
            socket.emit(&apos;addMessage&apos;, { content: &apos;&#x4F60;&#x597D;&apos; });
        }
    &lt;/script&gt;
&lt;/body&gt;

&lt;/html&gt;
</code></pre>
<h2 id="t24&#x53C2;&#x8003;">&#x53C2;&#x8003; <a href="#t24&#x53C2;&#x8003;"> # </a></h2>
<ul>
<li><a href="https://gitee.com/zhufengpeixun/chat-api">chat-api</a></li>
</ul>

        <div class="copyright">Powered by <a href="https://github.com/jaywcjlove/idoc" target="_blank">idoc</a>. Dependence <a href="https://nodejs.org">Node.js</a> run.</div>
    </div>
    
</div>

<script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script><script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.js"></script>
<script>
$('.warpper .page-toc ul ul li a').on('click',function(){
  $('.warpper .page-toc ul ul li a').removeClass('my-active')
  $(this).addClass('my-active')
})
  // if (!$('.understand-me').length) {
  //   var bar = $(window).height() - $('.navbar ').height() - $('.page-toc').position().top;
  //   var count = bar / 26 / 2;
  //   var barHeight = $('.page-toc').outerHeight();
  //   $('.page-toc li').eq(0).children('a').addClass('red');
  //   var arr = [];
  //   $("h1,h2,h3,h4,h5,h6").each(function () {
  //     arr.push($(this).position().top);
  //   });
  //   var timer
  //   function dark() {
  //     clearTimeout(timer)
  //      timer = setTimeout(function () {
  //      var top = Math.abs($('.page-toc > ul').position().top);
  //      var cur = $('.content').scrollTop();
  //      for (var i = arr.length; i >= 0; i--) {
  //        if (arr[i] <= cur) {
  //          break;
  //        }
  //      }
  //      if (i === -1) {
  //        i = 0;
  //      }
  //      $('.page-toc li a').removeClass('red');
  //      $('.page-toc li').eq(i).children('a').addClass('red');
  //      let height = $('.page-toc li').eq(i).position().top-$('.page-toc').height(); // 如果当前的offset出去了 回到中间可好？
  //      $('.page-toc').scrollTop(height+$('.page-toc').height()/2);
  //    },200)
  //   }

  //   $('.content').on('scroll', dark);
  // }
</script>
<style>

    /* ::-webkit-scrollbar{width:14px;}
    ::-webkit-scrollbar-track{background-color:transparent;}
    ::-webkit-scrollbar-thumb{background-color:transparent;}
    ::-webkit-scrollbar-thumb:hover {background-color:transparent}
    ::-webkit-scrollbar-thumb:active {background-color:transparent} */

    .page-toc > ul .red {
        background: #f3f3f3;
        z-index: 1;
        border-left: 3px solid #009a61;
        -webkit-transition: all .2s ease;
        transition: all .2s ease;
        color: #000
    }





</style>
</body>
</html>
